package org.chen.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.chen.common.vo.ResultVO;
import org.chen.entity.Model;
import org.chen.query.ModelQueryParams;
import org.chen.request.ModelRequest;
import org.chen.request.ModelUpdateRequest;
import org.chen.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/model")
public class ModelController {
    @Autowired
    private ModelService modelService;

    @PostMapping("/add")
    public ResultVO<Model> add(
            @RequestBody ModelRequest modelRequest) {

        try {
            Model model = modelService.saveModel(modelRequest);
            return ResultVO.success("添加模型成功", model);
        } catch (Exception e) {
            return ResultVO.fail("添加模型失败：" + e.getMessage());
        }
    }

    @PutMapping("/update")
    public ResultVO<Model> update(@RequestBody ModelUpdateRequest modelUpdateRequest) {
        try {
            Model model = modelService.updateModel(modelUpdateRequest);
            return ResultVO.success("更新模型成功", model);
        } catch (Exception e) {
            return ResultVO.fail("更新模型失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResultVO<Boolean> delete(@PathVariable Long id) {
        try {
            boolean result = modelService.deleteById(id);
            if (result) {
                return ResultVO.success("删除模型成功", true);
            } else {
                return ResultVO.fail("删除模型失败：模型不存在");
            }
        } catch (Exception e) {
            return ResultVO.fail("删除模型失败：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public ResultVO<Page<Model>> list(ModelQueryParams queryParams) {

        try {
            Page<Model> page = modelService.queryModels(queryParams);
            return ResultVO.success("查询模型成功", page);
        } catch (Exception e) {
            return ResultVO.fail("查询模型失败：" + e.getMessage());
        }
    }

    @GetMapping("/count_common")
    public ResultVO<Long> CountCommon(ModelQueryParams queryParams) {

        try {
            Long countCommon = modelService.CountCommon(queryParams);
            return ResultVO.success("查询模型数量成功", countCommon);
        } catch (Exception e) {
            return ResultVO.fail("查询模型数量失败：" + e.getMessage());
        }
    }

    @GetMapping("/getDetail/{id}")
    public ResultVO<Model> getDetailById(@PathVariable Long id) {

        try {
            Model model = modelService.getById(id);
            return ResultVO.success("查询模型成功", model);
        } catch (Exception e) {
            return ResultVO.fail("查询模型失败：" + e.getMessage());
        }
    }
}
